let ws = null

export const getClientWS = ({ notify } = {}) => {
    const notifyIsValid = typeof notify === 'function'
    if (!ws) {
        ws = new WebSocket(`ws://${location.host}/run`)
        notifyIsValid && ws.addEventListener('message', (ev) => notify(JSON.parse(ev.data)))

        return new Promise((resolve, reject) => {
            ws.onopen = () => resolve(ws)
            ws.onerror = () => reject()
        })
    } else {
        notifyIsValid && ws.addEventListener('message', (ev) => notify(JSON.parse(ev.data)))

        return Promise.resolve(ws)
    }
}